/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.mapper.*;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.CourseandclazzService;
import me.zhengjie.modules.system.domain.vo.CourseandclazzQueryCriteria;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author shitou
* @date 2024-04-21
**/
@Service
@RequiredArgsConstructor
public class CourseandclazzServiceImpl extends ServiceImpl<CourseandclazzMapper, Courseandclazz> implements CourseandclazzService {

    private final CourseandclazzMapper courseandclazzMapper;

    private final MyteachMapper myteachMapper;

    private final CourseandteachMapper courseandteachMapper;

    private final ClazzandstudentMapper clazzandstudentMapper;

    private final ClazzMapper clazzMapper;

    private final CourseMapper courseMapper;

    private final TeachMapper teachMapper;

    private final CoursechapterresourcesMapper coursechapterresourcesMapper;

    private final ClazzcourseMapper clazzcourseMapper;

    private final ClazzcourseteacherMapper clazzcourseteacherMapper;

    private final TeacherMapper teacherMapper;


    public List<Courseandclazz> queryCourseAndClazzMsg(Integer courseid) {
        return courseandclazzMapper.findMsg(courseid);
    }
    @Override
    public PageResult<Courseandclazz> queryAll(CourseandclazzQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(courseandclazzMapper.findAll(criteria, page));
    }

    public List<Course> getClazzCourse(CourseandclazzQueryCriteria criteria){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clazzId",criteria.getClazzId());
        List<Clazzcourse> courseAndClazzList = clazzcourseMapper.selectList(queryWrapper);
        List<Integer> courseIds = new ArrayList<>();
        for(Clazzcourse courseAndClazz:courseAndClazzList){
            courseIds.add(Math.toIntExact(courseAndClazz.getCourseid()));
        }
        QueryWrapper queryWrapper1 = new QueryWrapper<>();

        queryWrapper1.in("id",courseIds);
        if(criteria.getName()!=null){
            queryWrapper1.in("name",criteria.getName());
        }
        List<Course> courseList = new ArrayList<>();
        if(courseIds.size()!=0){
            courseList = courseMapper.selectList(queryWrapper1);
            //获取该班级拥有的资源数量
//            CourseChapterResources
            QueryWrapper queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("courseId",courseIds);
            List<Coursechapterresources> list = coursechapterresourcesMapper.selectList(queryWrapper2);

            QueryWrapper queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.in("courseId",courseIds);
            queryWrapper3.eq("clazzId",criteria.getClazzId());
            List<Clazzcourseteacher> clazzcourseteacherList = clazzcourseteacherMapper.selectList(queryWrapper3);
            System.out.println("===clazzcourseteacherList===="+clazzcourseteacherList);
            List<Integer> teacherIds = new ArrayList<>();
            for(Clazzcourseteacher clazzcourseteacher:clazzcourseteacherList){
                teacherIds.add(clazzcourseteacher.getTeacherId());
            }
            List<Teacher> teacherList = new ArrayList<>();
            if(teacherIds.size()!=0){
                QueryWrapper queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.in("id",teacherIds);
                teacherList = teacherMapper.selectList(queryWrapper4);
            }
            for(Course course:courseList){
                course.setImgNum(0);
                course.setVideoNum(0);
                course.setFileNum(0);
                course.setExerciseSetNum(0);
                course.setWorkNum(0);

                for(Coursechapterresources coursechapterresources:list){
                    if(course.getId() == coursechapterresources.getCourseId()){
                        if(coursechapterresources.getType() == 0){
                            course.setImgNum(course.getImgNum() + 1);
                        } else if(coursechapterresources.getType() == 1){
                            course.setVideoNum(course.getVideoNum()+1);
                        } else if(coursechapterresources.getType() == 2){
                            course.setFileNum(course.getFileNum()+1);
                        } else if(coursechapterresources.getType() == 2){
                            course.setExerciseSetNum(course.getExerciseSetNum()+1);
                        } else {
                            course.setWorkNum(course.getWorkNum()+1);
                        }
                    }
                }
                for(Clazzcourse clazzcourse:courseAndClazzList){
                    if(clazzcourse.getCourseid() == course.getId()){
                        course.setClazzCourseId(clazzcourse.getId());
                    }
                }
                List<Teacher> teacherList1 = new ArrayList<>();
                System.out.println("===teacherList==="+teacherList);

                for(Clazzcourseteacher clazzcourseteacher:clazzcourseteacherList){

                    if(clazzcourseteacher.getCourseId() == course.getId()){
                        for(Teacher teacher:teacherList){
                            if(Math.toIntExact(clazzcourseteacher.getTeacherId()) == Math.toIntExact(teacher.getId())){
                                System.out.println("===clazzcourseteacherList===");

                                teacherList1.add(teacher);
                            }
                        }
                    }
                }
                course.setTeacherList(teacherList1);
            }

        }

        return courseList;
    }

    public List<Teach> getClazzTeach(CourseandclazzQueryCriteria criteria){

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clazzId",criteria.getClazzId());
        List<Courseandclazz> courseAndClazzList = courseandclazzMapper.selectList(queryWrapper);
        List<Integer> courseIds = new ArrayList<>();
        List<Courseandteach> teachAndClazzList = new ArrayList<>();
        for(Courseandclazz courseAndClazz:courseAndClazzList){
            courseIds.add(Math.toIntExact(courseAndClazz.getCourseId()));

            QueryWrapper queryWrapper3 = new QueryWrapper<>();
            queryWrapper.eq("courseId",courseIds);
            teachAndClazzList = courseandteachMapper.selectList(queryWrapper3);
        }


        List<Integer> teachIds = new ArrayList<>();
        for(Courseandteach courseandteach:teachAndClazzList){
            teachIds.add(Math.toIntExact(courseandteach.getTeachid()));
        }
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("id",teachIds);
        if(criteria.getName()!=null){
            queryWrapper1.in("name",criteria.getName());
        }
        List<Teach> teachList = new ArrayList<>();
        if(teachIds.size()!=0){
            teachList = teachMapper.selectList(queryWrapper1);
        }

        return teachList;
    }

    @Override
    public List<Courseandclazz> queryAll(CourseandclazzQueryCriteria criteria){
        return courseandclazzMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Courseandclazz resources) {
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Courseandclazz resources) {
        Courseandclazz courseandclazz = getById(resources.getId());
        courseandclazz.copy(resources);
        saveOrUpdate(courseandclazz);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeCourseStatus(Courseandclazz resources) {
        QueryWrapper queryWrapper4 = new QueryWrapper();
        queryWrapper4.eq("clazzId",resources.getClazzId());
        queryWrapper4.eq("courseId",resources.getCourseId());
        Courseandclazz courseandclazz1 = courseandclazzMapper.selectOne(queryWrapper4);
        Courseandclazz courseandclazz = getById(courseandclazz1.getId());
        courseandclazz.copy(resources);
        saveOrUpdate(courseandclazz);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id",courseandclazz.getClazzId());
        Clazz clazz = clazzMapper.selectById(courseandclazz.getClazzId());
        if(clazz!=null){
            clazz.setInfo(resources.getInfo());
            clazz.setStatus(resources.getStatus());
            clazzMapper.update(clazz,queryWrapper1);
        }
        //获取课程绑定教材
        QueryWrapper<Courseandteach> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("courseId",resources.getCourseId());
        List<Courseandteach>  courseandteachList = courseandteachMapper.selectList(queryWrapper);
        List<Long> teachids = new ArrayList<>();
        for(Courseandteach courseandteach : courseandteachList){
            teachids.add(courseandteach.getTeachid());
        }

        //获取班级学生
        QueryWrapper<Clazzandstudent> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("clazzId",resources.getClazzId());
        List<Clazzandstudent>  clazzandstudentList = clazzandstudentMapper.selectList(queryWrapper2);
        List<Long> studentids =  new ArrayList<>();
        for(Clazzandstudent clazzandstudent : clazzandstudentList){
            studentids.add(clazzandstudent.getUserId());
        }

        //获取绑定学生
//        QueryWrapper<Myteach> queryWrapper3 = new QueryWrapper<>();
//        queryWrapper.in("teachId",teachids);
//        List<Myteach> myteachs = myteachMapper.selectList(queryWrapper3);
        //删除课程绑定教师
        QueryWrapper<Myteach> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("courseId",resources.getCourseId());
        myteachMapper.delete(queryWrapper3);

        for(Long studentid : studentids){
            for(Long teachid : teachids){
                Myteach myteach = new Myteach();
                myteach.setCourseId(Math.toIntExact(resources.getCourseId()));
                myteach.setUserId(Math.toIntExact(studentid));
                myteach.setTeachId(Math.toIntExact(teachid));
                myteachMapper.insert(myteach);
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Courseandclazz> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Courseandclazz courseandclazz : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("课程id", courseandclazz.getCourseId());
            map.put(" lastupdatetime",  courseandclazz.getLastupdatetime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}